package com.share.user.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.share.common.core.context.SecurityContextHolder;
import com.share.common.core.domain.R;
import com.share.common.core.exception.ServiceException;
import com.share.common.core.utils.bean.BeanUtils;
import com.share.common.core.web.domain.AjaxResult;
import com.share.user.api.model.LoginUserInfo;
import com.share.user.domain.UserInfo;
import com.share.user.domain.vo.UserVo;
import com.share.user.service.UserInfoService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private WxMaService wxMaService;

    /**
     * 远程调用查询用户信息
     * @param code
     * @return LoginUserInfo
     */
    @GetMapping("/info/{code}")
    public R<LoginUserInfo> getUserInfoByCode(@PathVariable String code) {
        String openid;
        try {
            log.info("微信端传过来的code：{}", code);
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openid = sessionInfo.getOpenid();
        } catch (Exception e) {
            log.error("获取OpenID异常: {}", e.getMessage());
            throw new ServiceException("获取OpenID异常");
        }

        UserInfo userInfo = userInfoService.getBaseMapper().selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getWxOpenId, openid));

        // 判断用户信息
        if (ObjectUtil.isNull(userInfo)) {
            // 添加用户信息
            UserInfo info = new UserInfo();
            info.setWxOpenId(openid);
            info.setNickname(String.valueOf(System.currentTimeMillis()));
            info.setAvatarUrl("https://img1.baidu.com/it/u=3346229584,3462787758&fm=253&fmt=auto&app=138&f=JPEG?w=342&h=342");
            userInfoService.getBaseMapper().insert(info);
            LoginUserInfo loginUserInfo = new LoginUserInfo();
            loginUserInfo.setId(info.getId());
            loginUserInfo.setNickname(info.getNickname());
            loginUserInfo.setAvatarUrl(info.getAvatarUrl());

            return R.ok(loginUserInfo);
        }

        LoginUserInfo loginUserInfo = new LoginUserInfo();
        loginUserInfo.setId(userInfo.getId());
        loginUserInfo.setNickname(userInfo.getNickname());
        loginUserInfo.setAvatarUrl(userInfo.getAvatarUrl());

        return R.ok(loginUserInfo);
    }

    @GetMapping("/getLoginUserInfo")
    public AjaxResult getLoginUserINfo(HttpServletRequest httpServletRequest) {
        Long userId = SecurityContextHolder.getUserId();
        UserInfo userInfo = userInfoService.getById(userId);
        UserVo userInfoVo = new UserVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return AjaxResult.success(userInfoVo);
    }

    @GetMapping("/info/{userId}")
    public R<UserInfo> getUserInfo(@PathVariable Long userId) {
        UserInfo userInfo = userInfoService.getById(userId);
        return R.ok(userInfo);
    }
}
